﻿package com.urbansquall.preloader
{
	import flash.display.*;
	import flash.events.*;
	import flash.filters.DropShadowFilter;
	import flash.filters.GlowFilter;
	import flash.utils.*;
	import flash.text.*;
	
	public class SimulatedPreloader extends MovieClip
	{
		protected function beginLoading() : void {}
		protected function updateLoading( a_percent : Number ) : void {}
		protected function endLoading() : void {}
		protected function get mainClassName() : String { return "Main"; }
				
		private var m_warningTextField : TextField;
		private var m_percent : int = 0;
		private var m_timer : Timer;
		
		public function SimulatedPreloader()
		{
			trace( "-------------------" );
			trace( "WARNING" );
			trace( "Your swf was compiled with the SimulatedPreloader. This should only be done when you are testing your preloader sublcass." );
			trace( "-------------------" );
			
			m_warningTextField = new TextField();
			addChild( m_warningTextField );
			m_warningTextField.autoSize = TextFieldAutoSize.RIGHT;
			m_warningTextField.textColor = 0xFFFFFF;
			m_warningTextField.text = "SIMULATING PRELOADING";
			m_warningTextField.x = this.stage.stageWidth - m_warningTextField.textWidth;
			m_warningTextField.filters = [ new GlowFilter( 0x000000 ) ];
			
			m_timer = new Timer( 50 );
			m_timer.addEventListener( TimerEvent.TIMER, firstCallback );
			m_timer.start();
		}
		
		private function firstCallback(a_event : Event) : void
		{
			beginLoading();
			m_timer.removeEventListener(TimerEvent.TIMER, firstCallback);
			m_timer.addEventListener(TimerEvent.TIMER, incrementPercent);
		}
		
		private function incrementPercent( a_event : Event ) : void
		{
			m_percent++;
			
			if( m_percent >= 101 )
			{
				m_timer.stop();
				m_timer.removeEventListener( TimerEvent.TIMER, incrementPercent );
				m_timer = null;
				
				startup();
				return;
			}
			
			updateLoading( m_percent / 100 );
		}
				
		private function startup():void
		{
			stop();
			
			endLoading();
			
			var MainClass:Class = getDefinitionByName( mainClassName ) as Class;
			if( MainClass == null )
			{
				throw new Error( "SimulatedPreloader:startup. There was no class matching [" + mainClassName + "]. You may need to override Preloader::mainClassName" );
			}
			
			var main : DisplayObject = new MainClass() as DisplayObject;
			if( main == null )
			{
				throw new Error( "SimulatedPreloader::startup. [" + mainClassName + "] needs to inherit from Sprite or MovieClip." );
			}
			
			addChildAt( main, 0 );
		}
		
	}
	
}